package com.swagger.wen.base;

import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.awt.*;

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;

/**
 * swagger2的配置类
 * Created by Think on 2018/6/14.
 */
@Configuration
public class Swagger2Config {

    @Value("${server.servlet.context-path}")
    private String pathMapping;

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档")//大标题
                .description(initContextInfo())//描述性语言
                .termsOfServiceUrl("服务条款")
                .contact(new Contact("wen","https://gitee.com/hxw_x/events","xxx")) //作者
                .license("我的api文档")//连接显示文字
                .version("1.0")//版本
                .licenseUrl("www.baidu.com")//连接地址
                .build();
    }

    private String initContextInfo() {
        StringBuffer sb = new StringBuffer();
        sb.append("REST API 设计在细节上有很多自己独特的需要注意的技巧，并且对开发人员在构架设计能力上比传统 API 有着更高的要求。").append("<br/>")
                .append("以下是本项目的API文档");
        return sb.toString();
    }

    @Bean
    public Docket restfulApi(){
        System.out.println("http://localhost:8081"+pathMapping+"/swagger-ui.html");
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("RestfulApi")
                .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false)
                //.pathMapping(pathMapping)// base，最终调用接口后会和paths拼接在一起
                .select()
                .paths(doFilteringRules()).build().apiInfo(apiInfo());
    }

    /**
     * 设置过滤规则 这里的过滤规则支持正则匹配
     //若有静态方法在此之前加载就会报集合相关的错误.
     *
     * @return
     */
    private Predicate<String> doFilteringRules() {
//		return Predicates.not(PathSelectors.regex("/error.*"));
//		return or(regex("/hello.*"), regex("/rest/adxSspFinanceManagement.*"));//success
        return or(regex("/api.*"), regex("/rest.*"));
    }


}
